package com.ruoyi.web.controller.degree;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.*;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.degree.domain.*;
import com.ruoyi.degree.service.*;
import com.ruoyi.system.service.ISysDictDataService;
import com.ruoyi.system.service.ISysDictTypeService;
import com.ruoyi.web.controller.tool.OssTools;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import com.qcloud.cos.COSClient;
import com.qcloud.cos.ClientConfig;
import com.qcloud.cos.auth.BasicCOSCredentials;
import com.qcloud.cos.auth.COSCredentials;
import com.qcloud.cos.model.PutObjectRequest;
import com.qcloud.cos.region.Region;
/**
 * 大学信息列表展示Controller
 *
 * @author ruoyi
 * @date 2025-07-24
 */
@RestController
@RequestMapping("/degree/schools")
public class BizSchoolsController extends BaseController
{
    @Autowired
    private IBizSchoolsService bizSchoolsService;
    @Autowired
    private IBizSchoolsProfessionsService bizSchoolsProfessionsService;
    @Autowired
    private IBizSchoolsVideosService bizSchoolsVideosService;
    @Autowired
    private IBizSchoolsDepartmentService bizSchoolsDepartmentService;
    @Autowired
    private ISysDictDataService dictDataService;
    @Autowired
    private IBizSchoolsMentorsService bizSchoolsMentorsService;

    @Autowired
    private IBizSchoolsProfessionsClassesService bizSchoolsProfessionsClassesService;
    /**
     * 查询大学信息列表展示列表
     */
    @PreAuthorize("@ss.hasPermi('degree:schools:list')")
    @GetMapping("/list")
    public TableDataInfo list(BizSchools bizSchools) {
        startPage();
        List<BizSchools> list = bizSchoolsService.selectBizSchoolsList(bizSchools);
        return getDataTable(list);
    }

    /**
     * 导出大学信息列表展示列表
     */
    @PreAuthorize("@ss.hasPermi('degree:schools:export')")
    @Log(title = "大学信息列表展示", businessType = BusinessType.EXPORT)

    @PostMapping("/export")
    public void export(HttpServletResponse response, BizSchools bizSchools) {
        List<BizSchools> schoolList = bizSchoolsService.selectBizSchoolsList(bizSchools);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        // ID转名称
        for (BizSchools school : schoolList) {
            if (school.getEduPlanId() != null) {
                //根据字典的DictType和DictValue获取DictLabel
                String dict = dictDataService.selectDictLabel("edu_plans", school.getEduPlanId().toString());
                if (dict != null) {
                    school.setEduPlanName(dict);
                }
            }
            if (school.getPlaceId() != null) {
                String dict = dictDataService.selectDictLabel("place", school.getPlaceId().toString());
                if (dict != null) {
                    school.setPlaceName(dict);
                }
            }
            // 过滤简介中的 <p> 和 </p>
            if (school.getIntro() != null) {
                String intro = school.getIntro().replace("<p>", "").replace("</p>", "");
                school.setIntro(intro);
            }

        }

        List<BizSchoolsProfessions> proList = bizSchoolsProfessionsService.selectBizSchoolsProfessionsList(new BizSchoolsProfessions());
        for (BizSchoolsProfessions pro : proList) {
            if (pro.getLanguages() != null) {
                String[] langIds = pro.getLanguages().split(",");
                List<String> langNames = new ArrayList<>();
                for (String langId : langIds) {
                    switch (langId.trim()) {
                        case "1":
                            langNames.add("中文");
                            break;
                        case "2":
                            langNames.add("西班牙语");
                            break;
                        case "3":
                            langNames.add("韩语");
                            break;
                        case "4":
                            langNames.add("英语");
                            break;
                        case "5":
                            langNames.add("俄语");
                            break;
                        default:
                            // 可选：处理未知语言
                            break;
                    }
                }
                pro.setLanguages(String.join("/", langNames));
            }

            if (pro.getOpeningDates() != null) {
                String[] openIds = pro.getOpeningDates().split(",");
                List<String> openNames = new ArrayList<>();
                for (String openId : openIds) {
                    switch (openId.trim()) {
                        case "1":
                            openNames.add("春季开学");
                            break;
                        case "2":
                            openNames.add("秋季开学");
                            break;
                        default:
                            // 可选：处理未知开学时间
                            break;
                    }
                }
                pro.setOpeningDates(String.join("/", openNames));
            }

            if (pro.getSchoolId() != null) {
                BizSchools school = bizSchoolsService.selectBizSchoolsById(pro.getSchoolId());
                if (school != null && school.getEduPlanId() != null) {
                    String dict = dictDataService.selectDictLabel("edu_plans", school.getEduPlanId().toString());
                    if (dict != null) {
                        pro.setEduPlanName(dict);
                    }
                }
            }
            if (pro.getSchoolId() != null) {
                BizSchools school = bizSchoolsService.selectBizSchoolsById(pro.getSchoolId());
                if (school != null) {
                    pro.setSchoolName(school.getName());
                }
            }
            if (pro.getEduPlanAdvantage() != null) {
                String advantage = pro.getEduPlanAdvantage()
                        .replace("<p>", "")
                        .replace("</p>", "")
                        .replace("<h2>", "")
                        .replace("</h2>", "");
                pro.setEduPlanAdvantage(advantage);
            }
            // 设置 degreeName，直接用数字映射
            if (pro.getDegree() != null) {
                String degreeName = "";
                switch (pro.getDegree().intValue()) {
                    case 1:
                        degreeName = "专科";
                        break;
                    case 2:
                        degreeName = "本科";
                        break;
                    case 3:
                        degreeName = "硕士";
                        break;
                    case 4:
                        degreeName = "博士";
                        break;
                    default:
                        degreeName = "未知";
                }
                pro.setDegreeName(degreeName);
            }

        }

        List<BizSchoolsMentors> mentorsList = bizSchoolsMentorsService.selectBizSchoolsMentorsList(new BizSchoolsMentors());
        for (BizSchoolsMentors mentors : mentorsList) {
            if (mentors.getSchoolId() != null) {
                BizSchools school = bizSchoolsService.selectBizSchoolsById(mentors.getSchoolId());
                if (school != null) {
                    mentors.setSchoolName(school.getName());
                }
            }
        }

        List<BizSchoolsProfessionsClasses> professionsClasses = bizSchoolsProfessionsClassesService.selectBizSchoolsProfessionsClassesList(new BizSchoolsProfessionsClasses());
        for (BizSchoolsProfessionsClasses proClass : professionsClasses) {
            // 专业
                BizSchoolsProfessions pro = bizSchoolsProfessionsService.selectBizSchoolsProfessionsById(proClass.getProfessionId());
                    proClass.setProfessionName(pro.getName());
                    // 院系
                    if (pro.getDepartmentId() != null) {
                        BizSchoolsDepartment dep = bizSchoolsDepartmentService.selectBizSchoolsDepartmentById(pro.getDepartmentId());
                        if (dep != null) {
                            proClass.setDeptName(dep.getDepartName());
                        }
                    }
                    // 院校
                    if (pro.getSchoolId() != null) {
                        BizSchools school = bizSchoolsService.selectBizSchoolsById(pro.getSchoolId());
                        if (school != null) {
                            proClass.setSchoolName(school.getName());
                            // 培养计划
                            if (school.getEduPlanId() != null) {
                                String eduPlanName = dictDataService.selectDictLabel("edu_plans", school.getEduPlanId().toString());
                                proClass.setEduPlanName(eduPlanName);
                            }
                        }
                    }

        }
        List<BizSchoolsDepartment> depList = bizSchoolsDepartmentService.selectBizSchoolsDepartmentList(new BizSchoolsDepartment());
        // 补充院校名称和培养计划名称
        for (BizSchoolsDepartment dep : depList) {
            if (dep.getSchoolId() != null) {
                BizSchools school = bizSchoolsService.selectBizSchoolsById(dep.getSchoolId());
                if (school != null) {
                    dep.setSchoolName(school.getName());
                    if (school.getEduPlanId() != null) {
                        String eduPlanName = dictDataService.selectDictLabel("edu_plans", school.getEduPlanId().toString());
                        dep.setEduPlanName(eduPlanName);
                    }
                }
            }
        }

        Map<String, List<?>> dataMap = new LinkedHashMap<>();
        dataMap.put("大学信息", schoolList);
        dataMap.put("专业信息", proList);
        dataMap.put("顾问留言", mentorsList);
        dataMap.put("课程信息", professionsClasses);
        dataMap.put("院系信息", depList);

        Map<String, Class<?>> classMap = new HashMap<>();
        classMap.put("大学信息", BizSchools.class);
        classMap.put("专业信息", BizSchoolsProfessions.class);
        classMap.put("顾问留言", BizSchoolsMentors.class);
        classMap.put("课程信息", BizSchoolsProfessionsClasses.class);
        classMap.put("院系信息", BizSchoolsDepartment.class);

        ExcelUtil.exportMultiSheetExcel(response, dataMap, classMap);
    }

    /**
     * 获取大学信息列表展示详细信息
     */
    @PreAuthorize("@ss.hasPermi('degree:schools:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(bizSchoolsService.selectBizSchoolsById(id));
    }

    /**
     * 新增大学信息列表展示
     */
    @PreAuthorize("@ss.hasPermi('degree:schools:add')")
    @Log(title = "大学信息列表展示", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody BizSchools bizSchools)
    {
        return success(bizSchoolsService.insertBizSchools(bizSchools));
    }

    /**
     * 修改大学信息列表展示
     */
    @PreAuthorize("@ss.hasPermi('degree:schools:edit')")
    @Log(title = "大学信息列表展示", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody BizSchools bizSchools)
    {
        return toAjax(bizSchoolsService.updateBizSchools(bizSchools));
    }

    /**
     * 删除大学信息列表展示
     */
    @PreAuthorize("@ss.hasPermi('degree:schools:remove')")
    @Log(title = "大学信息列表展示", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {

        return toAjax(bizSchoolsService.deleteBizSchoolsByIds(ids));
    }


    /**
     * 开关
     * @param id
     * @return
     */
    @PostMapping("/toggleHot/{id}")
    public AjaxResult toggleHot(@PathVariable Long id) {
        return toAjax(bizSchoolsService.toggleHot(id));
    }

    @PostMapping("/toggleShow/{id}")
    public AjaxResult toggleShow(@PathVariable Long id) {
        return toAjax(bizSchoolsService.toggleShow(id));
    }
    /**
     * Excel导入院校数据
     */
    @PostMapping("/importData")
    public AjaxResult importData(@RequestParam("file") MultipartFile file) throws Exception {
        // 缓存文件内容，避免 InputStream 只能读一次
        byte[] bytes = file.getBytes();
        InputStream schoolStream = new ByteArrayInputStream(bytes);
        InputStream depStream = new ByteArrayInputStream(bytes);
        InputStream proStream = new ByteArrayInputStream(bytes);
        InputStream proClaStream = new ByteArrayInputStream(bytes);
        InputStream mentorsStream = new ByteArrayInputStream(bytes);

        ExcelUtil<BizSchools> util = new ExcelUtil<>(BizSchools.class);
        // 读取指定 sheet（如 sheet 名为“大学基本信息”，索引 1，具体参数根据你的 ExcelUtil 实现调整）
        List<BizSchools> schoolList = util.importExcel("大学基本信息", schoolStream, 0);

        ExcelUtil<BizSchoolsDepartment> depUtil = new ExcelUtil<>(BizSchoolsDepartment.class);
        List<BizSchoolsDepartment> schoolDepList = depUtil.importExcel("院系信息", depStream, 0);

        ExcelUtil<BizSchoolsProfessions> proUtil = new ExcelUtil<>(BizSchoolsProfessions.class);
        List<BizSchoolsProfessions> schoolProList = proUtil.importExcel("专业信息", proStream, 0);

        ExcelUtil<BizSchoolsProfessionsClasses> proClaUtil = new ExcelUtil<>(BizSchoolsProfessionsClasses.class);
        List<BizSchoolsProfessionsClasses> schoolProClaList = proClaUtil.importExcel("专业课程", proClaStream, 0);

        //顾问留言
        ExcelUtil<BizSchoolsMentors> mentorsExcelUtil = new ExcelUtil<>(BizSchoolsMentors.class);
        List<BizSchoolsMentors> mentorsList = mentorsExcelUtil.importExcel("顾问留言", mentorsStream, 0);

        // 过滤掉所有字段都为空的对象
        schoolList = schoolList.stream()
                .filter(school -> {
                    if (school == null) return false;
                    return school.getName() != null && !"".equals(school.getName().trim())
                            || school.getIntro() != null && !"".equals(school.getIntro().trim())
                            || school.getPics() != null && !"".equals(school.getPics().trim())
                            || school.getLogo() != null && !"".equals(school.getLogo().trim())
                            || school.getIsHot() != null && !"".equals(school.getIsHot().toString().trim())
                            || school.getDocuments() != null && !"".equals(school.getDocuments().trim())
                            || school.getEndDate() != null
                            || school.getOrderNum() != null
                            || school.getTags() != null && !"".equals(school.getTags().trim())
                            || school.getPlaceId() != null
                            || school.getEduPlanId() != null
                            || school.getIsShow() != null
                            || school.getOpeningDateId() != null
                            || school.getCityName() != null && !"".equals(school.getCityName().trim());
                })
                .collect(java.util.stream.Collectors.toList());

        int successNum = 0;
        int failureNum = 0;
        StringBuilder failureMsg = new StringBuilder();
        int rowNum = 1;
        Map<String,Long> schoolNameList =  new HashMap<>();
        for (BizSchools school : schoolList) {
            try {
                //先获取培养计划类型，用于分辨同样大学多个不同类型的培养计划
                SysDictData dictEdu = dictDataService.selectDictByLabel("edu_plans", school.getEduPlanName());
                long dictEduId = 0;
                if (dictEdu != null) {
                    dictEduId= Long.parseLong(dictEdu.getDictValue());
                }else{
                    throw new Exception("大学 " + school.getName() + " 培养计划 " + school.getEduPlanName() + " 不存在，跳过导入");
                }

                //判断该大学是否已存在
                BizSchools queryExt = new BizSchools();
                queryExt.setName(school.getName());
                queryExt.setEduPlanId(dictEduId);
                List<BizSchools> existSchools = bizSchoolsService.selectBizSchoolsList(queryExt);
                if (existSchools != null && existSchools.size() > 0) {
                    school.setId(existSchools.get(0).getId());
                }
                SysDictData dict = dictDataService.selectDictByLabel("place", school.getPlaceName());
                if (dict != null) {
                    school.setPlaceId(Long.parseLong(dict.getDictValue()));
                } else {
                    throw new Exception("大学 " + school.getName() + " 地区 " + school.getPlaceName() + " 不存在，跳过导入");
                }
                school.setEduPlanId(dictEduId);
                school.setTags(school.getTags().replace("/", ","));
                school.setIsShow(1L);
                if(school.getId()!=null && school.getId()>0){
                    bizSchoolsService.updateBizSchools(school);
//                    //判断大学是否添加过
//                    for(String name : schoolNameList){
//                        if(school.getName().equals(name)){
//                            throw new Exception("大学 " + school.getName() + " 重复，跳过导入");
//                        }
//                    }
                    //删除这个大学下的专业信息
                    //删除这个大学下的专业课程信息
                    BizSchoolsProfessions delPro = new BizSchoolsProfessions();
                    delPro.setSchoolId(school.getId());
                    List<BizSchoolsProfessions> existPros = bizSchoolsProfessionsService.selectBizSchoolsProfessionsList(delPro);
                    for (BizSchoolsProfessions pro2 : existPros) {
                        //删除专业课程
                        BizSchoolsProfessionsClasses delProCla = new BizSchoolsProfessionsClasses();
                        delProCla.setProfessionId(pro2.getId());
                        List<BizSchoolsProfessionsClasses> existProClas = bizSchoolsProfessionsClassesService.selectBizSchoolsProfessionsClassesList(delProCla);
                        for (BizSchoolsProfessionsClasses proCla2 : existProClas) {
                            bizSchoolsProfessionsClassesService.deleteBizSchoolsProfessionsClassesById(proCla2.getId());
                        }
                        bizSchoolsProfessionsService.deleteBizSchoolsProfessionsById(pro2.getId());
                    }
                    //删除这个大学下的部门信息
                    BizSchoolsDepartment delDep = new BizSchoolsDepartment();
                    delDep.setSchoolId(school.getId());
                    List<BizSchoolsDepartment> existDeps = bizSchoolsDepartmentService.selectBizSchoolsDepartmentList(delDep);
                    for (BizSchoolsDepartment dep2 : existDeps) {
                        bizSchoolsDepartmentService.deleteBizSchoolsDepartmentById(dep2.getId());
                    }
                    //清除顾问留言
                    BizSchoolsMentors mentors = new BizSchoolsMentors();
                    mentors.setSchoolId(school.getId());
                    List<BizSchoolsMentors> existMentors = bizSchoolsMentorsService.selectBizSchoolsMentorsList(mentors);
                    for (BizSchoolsMentors men2 : existMentors) {
                        bizSchoolsMentorsService.deleteBizSchoolsMentorsById(men2.getId());
                    }
                }else{
                    bizSchoolsService.insertBizSchools(school);
                }
                schoolNameList.put(school.getName(),school.getEduPlanId());
                //插入院系数据
                for (BizSchoolsDepartment dep : schoolDepList) {
                    if (dep.getSchoolName().equals(school.getName()) && dep.getEduPlanName().equals(school.getEduPlanName()) ) {
                        dep.setSchoolId(school.getId());
                        bizSchoolsDepartmentService.insertBizSchoolsDepartment(dep);
                        //插入专业信息
                        for (BizSchoolsProfessions pro : schoolProList) {
                            if (pro.getSchoolName().equals(school.getName() )
                                    && pro.getDepartmentName().equals(dep.getDepartName()) && pro.getEduPlanName().equals(school.getEduPlanName()) ) {
                                //判断专业名称是否在数据库已经存在
                                if(pro.getId()!=null){
                                    throw new Exception("大学 " + school.getName() + " 专业 " + pro.getName() + " 已存在，跳过导入");
                                }
                                pro.setSchoolId(school.getId());
                                pro.setDepartmentId(dep.getId());
                                pro.setEduPlanAdvantage(pro.getEduPlanAdvantage() != null ? pro.getEduPlanAdvantage().replaceAll("\\s+", "") : null);
                                insertProfessions(pro);
                                //插入专业课程
                                for (BizSchoolsProfessionsClasses proCla : schoolProClaList) {
                                    if (proCla.getSchoolName().equals(school.getName())
                                            && proCla.getDeptName().equals(dep.getDepartName())
                                            && proCla.getProfessionName().equals(pro.getName())
                                            && proCla.getEduPlanName().equals(school.getEduPlanName()) ) {
                                        if(proCla.getId()!=null){
                                            throw new Exception("大学 " + school.getName() + " 专业 " + pro.getName() + " 课程 " + proCla.getName() + " 已存在，跳过导入");
                                        }
                                        proCla.setProfessionId(pro.getId());
                                        insertProfessionsClasses(proCla);
                                    }
                                }
                            }
                        }
                    }
                }
                //创建顾问留言
                for (BizSchoolsMentors mentors : mentorsList) {
                    if (mentors.getSchoolName().equals(school.getName()) ) {
                        mentors.setSchoolId(school.getId());
                        //随机头像1-5
                        mentors.setAvatar((int)(Math.random()*5));
                        bizSchoolsMentorsService.insertBizSchoolsMentors(mentors);
                    }
                }
                successNum++;
            } catch (Exception e) {
                failureNum++;
                failureMsg.append("<br/>第").append(rowNum)
                        .append("行导入失败：").append(e.getMessage());
                System.out.println(failureMsg.toString());
            }
            rowNum++;
        }
        if (failureNum == 0) {
            return AjaxResult.success("导入成功，共" + successNum + "条数据！");
        } else {
            return AjaxResult.error("成功导入" + successNum + "条，失败" + failureNum + "条。" + failureMsg.toString());
        }
    }

    //插入专业信息
    public void insertProfessions(BizSchoolsProfessions pro) throws Exception {
        //学位
        SysDictData dict = dictDataService.selectDictByLabel("degree_type", pro.getDegreeName());
        if (dict != null) {
            pro.setDegree(Long.parseLong(dict.getDictValue()));
        } else {
            throw new Exception("专业 " + pro.getName() + " 学位 " + pro.getDegreeName() + " 不存在，跳过导入");
        }
        if(pro.getLanguages()!=null){
            //教学语言
            String[] lanArr = pro.getLanguages().split("/");
            String lanStr ="";
            for (int i = 0; i < lanArr.length; i++) {
                SysDictData dictLan = dictDataService.selectDictByLabel("teachlanguage", lanArr[i]);
                if (dictLan == null) {
                    throw new Exception("专业 " + pro.getName() + " 语种 " + lanArr[i] + " 不存在，跳过导入");
                }
                if(i != lanArr.length-1){
                    lanStr += dictLan.getDictValue()+"," ;
                }else {
                    lanStr += dictLan.getDictValue();
                }
            }
            pro.setLanguages(lanStr);
        }

        //开学时间
        if(pro.getOpeningDates()!=null){
            String[] openDatesArr = pro.getOpeningDates().split("/");
            String openDatesStr ="";
            for (int i = 0; i < openDatesArr.length; i++) {
                SysDictData dictOpen = dictDataService.selectDictByLabel("opening_dates", openDatesArr[i]);
                if (dictOpen == null) {
                    throw new Exception("专业 " + pro.getName() + " 开学时间 " + openDatesArr[i] + " 不存在，跳过导入");
                }
                if(i != openDatesArr.length-1){
                    openDatesStr += dictOpen.getDictValue()+"," ;
                }else {
                    openDatesStr += dictOpen.getDictValue();
                }
            }
            pro.setOpeningDates(openDatesStr);
            pro.setOpeningDates(pro.getOpeningDates().replace("/", ","));
        }
        bizSchoolsProfessionsService.insertBizSchoolsProfessions(pro);
    }

    //插入专业课程
    public void insertProfessionsClasses(BizSchoolsProfessionsClasses proCla) throws Exception {
        String[] className = proCla.getName().split("/");
        if (className.length > 1) {
            for (int i = 0; i < className.length; i++) {
                BizSchoolsProfessionsClasses newProCla = new BizSchoolsProfessionsClasses();
                newProCla.setProfessionId(proCla.getProfessionId());
                newProCla.setName(className[i]);
                bizSchoolsProfessionsClassesService.insertBizSchoolsProfessionsClasses(newProCla);
            }
        }
    }


    @GetMapping("/importSchoolPics")
    public AjaxResult importSchoolPics() {
        OssTools ossTools = new OssTools();
        File dir = new File("D:\\degreeDataImport");
        List<String> dirNames = new ArrayList<>();
        File[] subDirs = dir.listFiles(File::isDirectory);
        if (subDirs != null) {
            for (File subDir : subDirs) {
                dirNames.add(subDir.getName());
            }
        }
        // 全局去重：MD5 -> URL
        Map<String, String> md5UrlMap = new HashMap<>();
        for (String dirName : dirNames) {
            System.out.println("开始导入" + dirName + "图片");
            BizSchools queryExt = new BizSchools();
            queryExt.setName(dirName);
            List<BizSchools> existSchools = bizSchoolsService.selectBizSchoolsList(queryExt);
            if (existSchools == null || existSchools.isEmpty()) {
                System.out.println("大学 " + dirName + " 不存在，跳过导入");
                continue;
            }
            if (existSchools.get(0).getPics() != null && !"".equals(existSchools.get(0).getPics().trim())) {
                System.out.println("大学 " + dirName + " 已经上传过图片，跳过导入");
                continue;
            }
            BizSchools school = existSchools.get(0);
            Set<String> picSet = new LinkedHashSet<>();
            File subDir = new File(dir, dirName);
            File[] files = subDir.listFiles((d, name) -> name.matches(".*\\.(jpg|png|jpeg|bmp|gif)$"));
            if (files != null) {
                for (File file : files) {
                    try (FileInputStream fis = new FileInputStream(file)) {
                        String md5 = DigestUtils.md5Hex(fis);
                        String ext = file.getName().substring(file.getName().lastIndexOf("."));
                        String ossFileName = md5 + ext;
                        String url;
                        if (md5UrlMap.containsKey(md5)) {
                            url = md5UrlMap.get(md5);
                            System.out.println("图片 " + file.getName() + " 已存在，复用 URL");
                        } else {
                            url = ossTools.uploadFile(file, ossFileName);
                            md5UrlMap.put(md5, url);
                            System.out.println("图片 " + file.getName() + " 上传成功，URL: " + url);
                        }
                        picSet.add(url);
                    } catch (Exception e) {
                        System.out.println("大学 " + dirName + " 图片 " + file.getName() + " 上传失败，跳过导入");
                    }
                }
                school.setPics(String.join(",", picSet));
                bizSchoolsService.updateBizSchools(school);
                System.out.println("大学 " + dirName + " 图片导入完成");
            }
        }
        System.out.println("所有大学图片导入完成");
        return AjaxResult.success("导入成功,共" + dirNames.size() + "个大学图片数据！");
    }

}
